using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyController : MonoBehaviour
{

    // 刚体
    private Rigidbody2D rigidbody2d;

    // 动画控制器
    private Animator animator;


    public float speed = 3.5f; // 速度

    // 轴向
    public bool isVerticle = true;

    // 方向
    private int direction = 1;



    // 方向改变间隔
    public float ChangeTime = 3.0f;

    // 方向改变计时器
    private float timer;


    // 是否损坏
    private bool isBroken = true;


    // Start is called before the first frame update
    void Start()
    {
        rigidbody2d = GetComponent<Rigidbody2D>();
        animator = GetComponent<Animator>();

        timer = ChangeTime;

        switchAnimation();
    }

    // Update is called once per frame
    void Update()
    {

        if (!isBroken)
        {

            return;
        }

        timer -= Time.deltaTime;
        if (timer < 0)
        {
            direction = -direction;
            switchAnimation();
            timer = ChangeTime;
        }
        Vector2 position = rigidbody2d.position;

        if (isVerticle)
        {
            position.y += Time.deltaTime * speed * direction;
        }
        else
        {
            position.x += Time.deltaTime * speed * direction;
        }


        rigidbody2d.MovePosition(position);
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        RubyController rubyController = collision.gameObject.GetComponent<RubyController>();
        if (rubyController != null)
        {
            rubyController.ChangeHealth(-1);
        }
    }

    // 切换动画
    private void switchAnimation()
    {
        //animator.SetFloat("MoveX", direction);
        //animator.SetBool("Verticle", isVerticle);
        if (isVerticle)
        {
            animator.SetFloat("MoveX", 0);
            animator.SetFloat("MoveY", direction);
        }
        else
        {
            animator.SetFloat("MoveX", direction);
            animator.SetFloat("MoveY", 0);
        }
    }


    public void Fix()
    {
        isBroken = false;
        rigidbody2d.simulated = false; // 不会再和其他物体发生碰撞检测
        animator.SetTrigger("Fixed");
    }
}
